

// src/components/ChatAssistant.jsx

import React, { useState, useEffect, useRef } from 'react';
import {
  Drawer,
  Input,
  Button,
  List,
  Avatar,
  Spin,
  message
} from 'antd';
import {
  MessageOutlined,
  SendOutlined,
  UserOutlined,
  RobotOutlined
} from '@ant-design/icons';
import './ChatAssistant.scss';
import axios from 'axios';
import chatIcon from '../../assets/img/WhaleAI.png'; // 确保路径正确

export default function ChatAssistant() {
  const [visible, setVisible] = useState(false);
  const [msgs, setMsgs] = useState([]);
  const [input, setInput] = useState('');
  const [loadingInit, setLoadingInit] = useState(false);
  const [sending, setSending] = useState(false);
  const listRef = useRef(null);

  // 滚动到底
  useEffect(() => {
    listRef.current?.scrollTo(0, listRef.current.scrollHeight);
  }, [msgs]);

  // 打开时加载
  useEffect(() => {
    if (!visible) return;
    setLoadingInit(true);
    setMsgs([{ from: 'assistant', content:  '您好！我是IntelliWhale智能投资助手，我可以为您分析持仓风险并给出建议！' }]);

    (async () => {
      try {
        const uid = JSON.parse(localStorage.getItem('user_info')).id;
        const res = await axios.get('/api/risk/stock_scores', {
          params: { uid },
          headers: { Authorization: `Bearer ${localStorage.getItem('jwt_token')}` }
        });
        const { summary } = res.data;
        setMsgs(m => [...m, { from: 'assistant', content: summary }]);
      } catch {
        message.error('无法加载风险建议');
        setMsgs(m => [...m, { from: 'assistant', content: '抱歉，未能获取风险建议，请稍后重试。' }]);
      } finally {
        setLoadingInit(false);
      }
    })();
  }, [visible]);

  const open = () => setVisible(true);
  const close = () => setVisible(false);

  // 发送
  const send = async () => {
    const text = input.trim();
    if (!text) return;
    setMsgs(m => [...m, { from: 'user', content: text }]);
    setInput('');
    setSending(true);

    try {
      const uid = JSON.parse(localStorage.getItem('user_info')).id;
      const riskDataRes = await axios.get('/api/risk/stock_scores', {
        params: { uid },
        headers: { Authorization: `Bearer ${localStorage.getItem('jwt_token')}` }
      });
      const riskData = riskDataRes.data;

      const res = await fetch('/api/ai/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: text, context: riskData })
      });
      const { reply } = await res.json();
      setMsgs(m => [...m, { from: 'assistant', content: reply }]);
    } catch {
      setMsgs(m => [...m, { from: 'assistant', content: '抱歉，IntelliWhale助手暂时无法响应，请稍后再试。' }]);
    } finally {
      setSending(false);
    }
  };

  const handleKeyDown = e => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  return (
    <>
      <Button
        type="text"
        
        className="chat-trigger"
        onClick={open}
        >
        <img
         src={chatIcon}
         alt="Chat"
         style={{ width: 200, height: 200 }}
        />
      </Button>

      <Drawer
        title="IntelliWhale智能投顾助手"
        placement="right"
        onClose={close}
        visible={visible}
        width={350}
        className="chat-drawer"
        headerStyle={{ background: '#4e6cef', color: '#fff', border: 'none' }}
        bodyStyle={{ padding: 0 }}
      >
        {loadingInit ? (
          <div className="chat-loading">
            <Spin tip="加载中..." />
          </div>
        ) : (
          <div className="chat-container" ref={listRef}>
            <List
              dataSource={msgs}
              renderItem={(item, idx) => (
                <List.Item
                  className={`chat-item ${item.from}`}
                  key={idx}
                >
                  <Avatar
                    icon={item.from === 'user' ? <UserOutlined /> : <RobotOutlined />}
                    className="chat-avatar"
                  />
                  <div className="chat-bubble">
                    {item.content}
                    {sending && idx === msgs.length - 1 && item.from === 'assistant' && (
                      <Spin size="small" className="bubble-loading" />
                    )}
                  </div>
                </List.Item>
              )}
            />
          </div>
        )}

        <div className="chat-input-bar">
          <Input.TextArea
            rows={2}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="请输入，Enter 发送，Shift+Enter 换行"
            bordered={false}
            className="chat-input"
          />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={send}
            loading={sending}
            className="send-btn"
          />
        </div>
      </Drawer>
    </>
  );
}
